"""
    Delicious API handler
    
    Acts as transparent proxy but enforces the rate limit
    imposed by the Del.icio.us API
    
    @author: Jean-Lou Dupont
"""

import os
import sys
import logging
import string
import base64

import wsgiref.handlers
from google.appengine.ext           import webapp
from google.appengine.api           import users
from google.appengine.api           import memcache
from google.appengine.api           import urlfetch

from libs.user.prefs import UserPrefs

class DeliciousApiHandler(webapp.RequestHandler):
    """
        Acts as transparent proxy but enforces the 1query/second rate
    """
    
    _API = 'https://api.del.icio.us/v1/%s'
    
    def get(self, query):
        
        user = users.get_current_user()

        userPrefs = None

        if user:
            userPrefs = UserPrefs.create( user )
        
        if not userPrefs:
            self.response.set_status( 401 ) #Unauthorized
            return

        try:
            username = userPrefs.delicious_username
            password = userPrefs.delicious_password
        except:
            self.response.set_status( 401 ) #Unauthorized
            return
        
        #Rate Limit enforcement
        token = memcache.get( "api/delicious/%s" % user )
        if token:
            logging.info('api/delicious: throttled user[%s]' % user)
            self.response.set_status( 503 ) #Service unavailable
            self.response.out.write( "{ 'code':'503', 'msg':'rate limit' }" )
            return

        #Performs the query
        url = DeliciousApiHandler._API % query
        auth = "Basic %s" % ( base64.encodestring("%s:%s" % (username, password)).strip() )

        result = urlfetch.fetch(url=url, method=urlfetch.GET, headers={'Authorization':auth})

        #Escape the string 
        data = result.content.replace('"', r'\"')

        response = "{ \"code\": \"%s\", \"data\":\"%s\" }" % ( result.status_code, data )
        
        #self.response.headers["Content-Type"] = "application/json"
        self.response.out.write( response )
        
        #Don't forget the rate limit indicator
        memcache.add( "api/delicious/%s" % user, "timeout",  time=1) #1second
        
        logging.info("api/delicious, url[%s] auth[%s]" %(url, auth) )
   
       
#========================================================================================================
def main():
  application = webapp.WSGIApplication([('/api/delicious/(.*)', DeliciousApiHandler) ], debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
    main()        